import {
    createStore
} from 'vuex'

import createPersistedState from "vuex-persistedstate";  //安装cnpm install --save vuex-persistedstate
import api from "@/http/api.js"
import { Toast } from 'vant';
export default createStore({
    state: {
        userInfo: null,
        menuList: [],
        buttonList: [],
        active: 0,
        isShow: true,//默认显示tabBar
        code: "",
        cart: [],//购物车列表
        checked: true,//购物车全选
        znum: 0,
        zprice: 0
    },
    mutations: {
        // 购物车列表数据
        cartlist(state, data) {
            state.cart = data
        },
        // 单选
        changeCheckx(state, index) {
            state.cart[index].check = !state.cart[index].check
            // 判断全选状态
            state.checked = state.cart.every(item => {
                return item.check == true
            })
            // 统计总价格总数量
            let num = 0
            let price = 0
            state.cart.forEach(item => {
                if (item.check) {
                    num += item.num
                    price += item.price * item.num
                }
            })
            state.znum = num
            state.zprice = price
        },
        // 全选
        checkAll(state) {
            state.checked = !state.checked
            state.cart.forEach(item => {
                return item.check = state.checked
            })
        },
        changeCode(state, code) {
            state.code = code
        },
        setTab(state, obj) {
            state.active = obj.act
            state.isShow = obj.isShow
        },
        setUserInfo(state, data) {
            state.userInfo = data
        },

        setSignOut(state) {
            state.userInfo = null
            state.menuList = []
            state.buttonList = []
        },
        setMenuList(state, data) {
            if (data.length == 0) {
                state.menuList = null
            } else {
                state.menuList = data
            }
        },
        setButtonList(state, data) {
            state.buttonList = data
        },
    },
    getters: {
        getMenuList(state) {
            return state.menuList
        }
    },
    actions: {
        userInfos({
            commit
        }, data) {
            commit("setUserInfo", data)
        },

        signOuts({
            commit
        }) {
            commit("setSignOut")
        },

        getLists({
            commit
        }, data) {
            api.getMenu().then(res => {
                commit("setMenuList", res.data.menuList)
                commit("setButtonList", res.data.btnList)
            })
        },
    },
    modules: {},
    plugins: [
        createPersistedState({
            storage: window.localStorage,
            key: "store",
            render(state) {
                return {
                    ...state
                };
            }
        })
    ]
})
